package com.han.nettytestdemo.connector;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

public class PollingUtils {

    private static final int MSG_POLLING = 0x0001;


    private volatile static PollingUtils instance = null;

    private TreadReadGetImsState treadReadGetImsState;

    /*
     * plc数据
     */
    private ImsStateListener imsStateListener;

    public ImsStateListener getImsStateListener() {
        return imsStateListener;
    }

    public void setImsStateListener(ImsStateListener imsStateListener) {
        this.imsStateListener = imsStateListener;
    }

    public PollingUtils() {
    }

    public static PollingUtils getInstance() {
        if (instance == null) {
            synchronized (PollingUtils.class) {
                if (instance == null) {
                    instance = new PollingUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 开始轮询
     */
    public void startTime() {
        startImsState();//开启密集架状态同步
    }

    /**
     * 开启读取plc状态线程
     * 定时读取密集架状态
     * <p>
     * systemSet.getPollTime()：设置页面设置
     */
    private void startImsState() {
        treadReadGetImsState = new TreadReadGetImsState();
        treadReadGetImsState.setImsStateListener(model -> {
            if (imsStateListener!=null){
                imsStateListener.onImsState(model);
            }
        });
        doImsStatePolling(true);
    }

    private void stopImsState() {
        if (null != handlerImsState) {
            handlerImsState.removeMessages(MSG_POLLING);
        }
    }

    /**
     * 读取plc状态线程
     */
    private Handler handlerImsState = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_POLLING:
                    doImsStatePolling(false);
                    break;
            }
        }
    };

    private void doImsStatePolling(Boolean isFirst) {
        if (isFirst) {
            handlerImsState.removeMessages(MSG_POLLING);
            handlerImsState.sendEmptyMessageDelayed(MSG_POLLING, 100);
            return;
        }
        treadReadGetImsState.startRun();
        handlerImsState.sendEmptyMessageDelayed(MSG_POLLING, 100);
    }


    /**
     * 结束轮询
     */
    public void stopTime() {
        stopImsState();
    }


}
